<template>
  <view class="login-box">
    <image class="login-logo" src="https://mp-7bd569d5-2369-48a6-b477-e8c6b6ccf6ce.cdn.bspapp.com/10011693836581_.pic.jpg" mode="widthFix"></image>
    <view class="login-title">城市车位，您的车位选择</view>
    <!-- #ifdef H5 -->
    <view class="input">
      <view class="input-label">用户名：</view>
      <input class="input-txt" type="text" v-model="username" placeholder="请输入用户名">
    </view>
    <view class="input">
      <view class="input-label">密码：</view>
      <input type="password" v-model="password" placeholder="请输入密码">
    </view>
    <view class="input" v-if="invite_code">
      <view class="input-label">邀请码：</view>
      <input type="text" disabled v-model="invite_code" placeholder="请输入密码">
    </view>
    <view @tap="clickBtn">
      <button style="color: #fff;
      background-color: #005ECD;
      border-radius: 100rpx;" class="login-btn" :class="{ 'pointer-none': !isChecked }" type="default" @tap="pageLogin"
        >登录</button>
    </view>
    <!-- #endif -->
    <!-- #ifdef MP -->
   <view class="input" v-if="!is_bind">
      <view class="input-label">邀请码：</view>
      <input type="text" v-model="invite_code" placeholder="如有邀请码,请输入">
    </view>
      <view @tap="clickBtn">
        <button style="color: #fff;
        background-color: #005ECD;
        border-radius: 100rpx;" class="login-btn" :class="{ 'pointer-none': !isChecked }" type="default"
          open-type="getPhoneNumber" @getphonenumber="loginByWeixinPhoneNumber1">手机号登录</button>
      </view>
    <!-- #endif -->
    <view class="sign">
      <img v-if="isChecked" @tap="checkFn" class="sign-1" src="https://mp-7bd569d5-2369-48a6-b477-e8c6b6ccf6ce.cdn.bspapp.com/方形选中.svg" alt="">
      <img v-else @tap="checkFn" class="sign-1" src="https://mp-7bd569d5-2369-48a6-b477-e8c6b6ccf6ce.cdn.bspapp.com/方形未选中.svg" alt="">
      <view class="sign-2" @tap="checkFn">勾选代表您已阅读并同意</view>
      <view @tap="goXieyi('64eda8d7189f866d65a46911')" class="sign-3">《用户服务协议》 </view>、
      <view @tap="goXieyi('64eda8e086206658e9e15eb9')" class="sign-3">《隐私政策》</view>
    </view>
    <!-- #ifdef H5 -->
     <view class="sign-2">如未注册，登录即注册新用户</view>
    <!-- #endif -->
  </view>
</template>

<script>
  export default {
    data() {
      return {
        isChecked: false,
        encryptedKey: '',
        username: '',
        password: '',
        invite_code: '',
        is_bind: false, // 是否绑定过邀请人
      }
    },
    onShow() {
      // #ifdef MP
      this.init()
      // #endif
      if ( uni.getStorageSync('invite_code')) {
        this.invite_code = uni.getStorageSync('invite_code')
      }
      this.is_bind = uni.getStorageSync('is_bind')
    },
    methods: {
      init() {
        let that = this;
        vk.userCenter.code2SessionWeixin({
          data: {
            needCache: true
          },
          success: (data) => {
            that.encryptedKey = data.encryptedKey;
          },
        });
      },
      clickBtn() {
        if (!this.isChecked) {
          uni.showToast({
            title: '请阅读并勾选相关协议',
            icon: 'none'
          });
        }
      },
      checkFn() {
        this.isChecked = !this.isChecked
      },
      async pageLogin() {
        let str = ''
        if (!this.username) {
          str = '请输入用户名'
        }
        if (!this.password) {
          str = '请输入密码'
        }
        if (str) {
          return vk.toast(str,'none');
        }
        // 账号密码登录
        let that = this;
        if(!vk.pubfn.validator(that.username)){
        	vk.toast('账号至少4位数',"none");
        	return;
        }
        if(!vk.pubfn.test(that.password, 'pwd')){
        	vk.toast('密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线',"none");
        	return;
        }
        let obj = {
            username: this.username,
            password: this.password
          }
        if (this.invite_code) {
          obj.myInviteCode = this.invite_code
        }
        let data = await this.vk.callFunction({
          url: 'user/pub/loginPwd',
          title: 'loading...',
          data: obj
        })
        if (data.code == 0) {
          vk.toast('登录成功','none');
          setTimeout(() => {
            uni.navigateBack()
          }, 500)
          let obj = {}
          if (data.userInfo.water_amount==0 && data.userInfo.nickname && data.userInfo.avatar && !this.invite_code) {
              return 
           }
          if (!data.userInfo.water_amount) {
            obj.water_amount = 0
          }
          if (!data.userInfo.nickname) {
            obj.nickname = data.userInfo.mobile
          }
          if (!data.userInfo.avatar) {
            obj.avatar = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
          }
          if (this.invite_code) {
            obj.invite_code = this.invite_code
          }
          vk.callFunction({
            url: 'user/kh/updateUserPid',
            data: obj,
            success: () => {
              if (obj.invite_code) {
                uni.removeStorageSync('invite_code')
              }
              uni.setStorageSync('is_bind', true)
            }
          })
        }
      },
      goXieyi(id) {
        uni.navigateTo({
          url: '/pages/xieyi/xieyi?id=' + id
        })
      },
      updateCode(obj, flag) {
        let invite_code = this.invite_code || uni.getStorageSync('invite_code')
        if (invite_code) {
          obj.invite_code = invite_code
        }
        if (flag) {
          // 第一次更新
          vk.callFunction({
            url: 'user/kh/updateUserPid',
            data: obj,
            success: () => {
              if (obj.invite_code) {
                uni.removeStorageSync('invite_code')
              }
              uni.setStorageSync('is_bind', true)
              uni.$emit('loginSuccess')
            }
          })
        } else {
          if (obj.invite_code) {
            vk.callFunction({
              url: 'user/kh/updateUserPid',
              data: {
                invite_code
              },
              success: () => {
                if (obj.invite_code) {
                  uni.removeStorageSync('invite_code')
                }
                uni.setStorageSync('is_bind', true)
                uni.$emit('loginSuccess')
              }
            })
          } else {
             uni.$emit('loginSuccess')
          }
        }
      },
      // 使用微信绑定的手机号登录/注册（新方式）
      loginByWeixinPhoneNumber1(e) {
        let that = this;
        let {
          code
        } = e.detail;
        if (!code) {
          return false;
        }
        vk.userCenter.loginByWeixinPhoneNumber({
          data: {
            code,
            encryptedKey: that.encryptedKey
          },
          success(data) {
            console.log(data)
            vk.toast(data.msg, 'none');
            // 更新父id
            uni.switchTab({
              url: '/pages/index/index'
            })
            let obj = {}
            if (!data.userInfo.username) {
              obj.water_amount = 0
              obj.balance = 0
              obj.water_amount_back = 0
              obj.username = data.userInfo.mobile
              obj.avatar = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
              that.updateCode(obj, true)
            } else {
              that.updateCode(obj, false)
            }
          }
        });
      },
    }
  }
</script>

<style lang="scss">
  .pointer-none {
    pointer-events: none;
  }

  .login {
    &-box {
      background-color: #fff;
      padding: 30rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-evenly;
    }

    &-logo {
      width: 200rpx;
      height: 200rpx;
    }

    &-title {
      font-family: 'Inter';
      font-style: normal;
      font-weight: 500;
      font-size: 30rpx;
      color: #000000;
      margin-top: 40rpx
    }

    &-btn {
      width: 660rpx;
      height: 66rpx;
      text-align: center;
      line-height: 66rpx;
      font-family: PingFang SC;
      font-size: 32rpx;
      font-style: normal;
      font-weight: 600;
      margin-top: 40rpx;
    }
  }
  .input {
    width: 660rpx;
    height: 46rpx;
    display: flex;
    align-items: center;
    padding: 10rpx;
    border: 1px solid #d9d9d9;
    border-radius: 100rpx;
    margin-top: 40rpx;
    &-txt {
      font-family: PingFang SC;
      font-size: 28rpx;
      font-style: normal;
      font-weight: bold;
      flex: 1;
    }
    &-label {
      font-family: PingFang SC;
      font-size: 28rpx;
      font-style: normal;
      padding-left: 20rpx;
      width: 200rpx;
    }
  }
  .sign {
    display: flex;
    flex-wrap: wrap;
    margin-top: 40rpx;
    height: 60rpx;
    &-2 {
      font-family: 'Inter';
      font-style: normal;
      font-weight: 400;
      font-size: 24rpx;
      color: #000000;
    }
    &-1 {
      width: 32rpx;
      height: 32rpx;
      margin-right: 4rpx;

      &-checked {
        background: #005ECD;
      }
    }

    &-3 {
      color: #005ECD;
      font-family: 'Inter';
      font-style: normal;
      font-weight: 400;
      font-size: 24rpx;
    }
  }
</style>